<template>
  <van-field label="上传视频" required>
    <template #input>
      <van-uploader
          v-model="fileList"
          :before-read="beforeRead"
          :max-size="maxSize"
          :max-count="1"
          accept="video/*"
          :deletable="true"
          :after-read="afterRead"
          @delete="deleteFile"
      >
        <template #preview-cover="{ file }">
          <div class="preview-cover van-ellipsis">{{ file.name }}</div>
        </template>
      </van-uploader>
    </template>
  </van-field>
</template>

<script setup>
import { computed, ref } from "vue";
import { showFailToast, showSuccessToast } from "vant";
import { uploadVideo } from "@/api/upload"; // assumes a function uploadVideo() that uploads the video to the server
const fileList = ref([]);
const maxSize = 200 * 1024 * 1024;
const props = defineProps(["videoUrl"]);
const emit = defineEmits(["update:videoUrl"]);
const uploadVideoUrl = computed({
  get() {
    return props.videoUrl;
  },
  set(val) {
    emit("update:videoUrl", val);
  },
});

// 上传前校验
const beforeRead = (file) => {
  if (!/video\/\w+/.test(file.type)) {
    showFailToast("请选择视频文件");
    return false;
  }
  if (file.size > maxSize) {
    showFailToast(`文件大小不能超过200MB`);
    return false;
  }
  return true;
};

// 上传视频
const afterRead = async (file) => {
  try {
    const data = new FormData(); // 创建form对象
    data.append("file", file.file); // 通过append向form对象添加数据
    const result = await uploadVideo(data); // 异步上传视频
    if (result.msg !== "请求成功") {
      showFailToast("上传失败，请重试");
      return;
    }
    const videoUrl = result.data.uploadUrl || ""; // 获取视频地址
    if (!videoUrl || videoUrl === "") {
      showFailToast("视频地址出现问题，请重试");
      return;
    }
    uploadVideoUrl.value = videoUrl; // 将视频地址赋值给表单
    showSuccessToast("上传成功");
  } catch (error) {
    console.log(error, "<<<-----error");
    uploadVideoUrl.value = ""; // 清空视频地址
    fileList.value = []; // 清空上传视频列表
    showFailToast("上传失败，请重试");
  }
};

const deleteFile = () => {
  uploadVideoUrl.value = ""; // 清空视频地址
  fileList.value = []; // 清空上传视频列表
};
</script>

<style scoped>
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  border-radius: 12px;
  background: rgba(0, 0, 0, 0.3);
}
</style>
